import React, { useState, useEffect } from 'react';
import { 
  Card, Form, Switch, Button, Divider, message, Spin, 
  Select, Input, Table, Tag, Slider, Space, Popconfirm 
} from 'antd';
import { 
  SaveOutlined, UndoOutlined, ShieldOutlined, 
  PlusOutlined, DeleteOutlined, EditOutlined 
} from '@ant-design/icons';
import axios from 'axios';

const { Option } = Select;
const { TextArea } = Input;

const SensitiveContentSettings = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [patterns, setPatterns] = useState([]);
  const [editingPattern, setEditingPattern] = useState(null);

  // 加载设置
  useEffect(() => {
    fetchSettings();
  }, []);

  // 获取敏感内容设置
  const fetchSettings = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/settings/sensitive-content');
      form.setFieldsValue(response.data.settings);
      setPatterns(response.data.patterns || []);
    } catch (error) {
      console.error('获取敏感内容设置失败:', error);
      message.error('获取敏感内容设置失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存设置
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);
      
      await axios.post('/api/settings/sensitive-content', {
        settings: values,
        patterns
      });
      message.success('敏感内容设置已保存');
    } catch (error) {
      console.error('保存敏感内容设置失败:', error);
      message.error('保存敏感内容设置失败');
    } finally {
      setSaving(false);
    }
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
    fetchSettings();
  };

  // 添加新模式
  const handleAddPattern = () => {
    const newPattern = {
      id: Date.now(),
      pattern: '',
      type: 'regex',
      description: '',
      isActive: true
    };
    setPatterns([...patterns, newPattern]);
    setEditingPattern(newPattern.id);
  };

  // 保存模式
  const handleSavePattern = (id, values) => {
    const updatedPatterns = patterns.map(p => 
      p.id === id ? { ...p, ...values } : p
    );
    setPatterns(updatedPatterns);
    setEditingPattern(null);
  };

  // 删除模式
  const handleDeletePattern = (id) => {
    const updatedPatterns = patterns.filter(p => p.id !== id);
    setPatterns(updatedPatterns);
  };

  // 渲染编辑状态或静态显示
  const renderPatternColumns = () => [
    {
      title: '模式',
      dataIndex: 'pattern',
      key: 'pattern',
      render: (text, record) => {
        if (editingPattern === record.id) {
          return (
            <Input 
              defaultValue={text} 
              onChange={e => handleSavePattern(record.id, { pattern: e.target.value })}
              placeholder="输入正则表达式或关键词"
            />
          );
        }
        return text;
      }
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (text, record) => {
        if (editingPattern === record.id) {
          return (
            <Select 
              defaultValue={text} 
              style={{ width: 120 }}
              onChange={value => handleSavePattern(record.id, { type: value })}
            >
              <Option value="regex">正则表达式</Option>
              <Option value="keyword">关键词</Option>
              <Option value="phone">电话号码</Option>
              <Option value="id">身份证号</Option>
              <Option value="bank">银行卡号</Option>
            </Select>
          );
        }
        
        const typeColor = {
          regex: 'blue',
          keyword: 'green',
          phone: 'orange',
          id: 'red',
          bank: 'purple'
        };
        
        const typeText = {
          regex: '正则表达式',
          keyword: '关键词',
          phone: '电话号码',
          id: '身份证号',
          bank: '银行卡号'
        };
        
        return <Tag color={typeColor[text]}>{typeText[text]}</Tag>;
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      render: (text, record) => {
        if (editingPattern === record.id) {
          return (
            <Input 
              defaultValue={text} 
              onChange={e => handleSavePattern(record.id, { description: e.target.value })}
              placeholder="输入描述"
            />
          );
        }
        return text;
      }
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 80,
      render: (active, record) => {
        if (editingPattern === record.id) {
          return (
            <Switch 
              checked={active} 
              onChange={checked => handleSavePattern(record.id, { isActive: checked })}
            />
          );
        }
        return <Tag color={active ? 'green' : 'gray'}>{active ? '启用' : '禁用'}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space>
          {editingPattern === record.id ? (
            <Button 
              type="primary" 
              size="small" 
              onClick={() => setEditingPattern(null)}
            >
              完成
            </Button>
          ) : (
            <Button 
              icon={<EditOutlined />} 
              size="small" 
              onClick={() => setEditingPattern(record.id)}
            />
          )}
          
          <Popconfirm
            title="确定要删除此模式吗?"
            onConfirm={() => handleDeletePattern(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            />
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <Spin spinning={loading}>
      <Card 
        title={
          <div>
            <ShieldOutlined style={{ marginRight: 8 }} />
            敏感内容设置
          </div>
        }
        extra={
          <div>
            <Button 
              style={{ marginRight: 8 }} 
              icon={<UndoOutlined />} 
              onClick={handleReset}
            >
              重置
            </Button>
            <Button 
              type="primary" 
              icon={<SaveOutlined />} 
              onClick={handleSave}
              loading={saving}
            >
              保存
            </Button>
          </div>
        }
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            enableSensitiveContentFilter: true,
            filterPhoneNumbers: true,
            filterIdNumbers: true,
            filterBankCardNumbers: true,
            filterLongDigits: true,
            filterCustomPatterns: true,
            enableImageContentDetection: false,
            imageSensitivityLevel: 3,
            treatAsWarning: false,
            adminBypassFilter: true
          }}
        >
          <Divider orientation="left">基本过滤设置</Divider>
          
          <Form.Item
            name="enableSensitiveContentFilter"
            label="启用敏感内容过滤"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item
            name="adminBypassFilter"
            label="管理员绕过过滤"
            valuePropName="checked"
            tooltip="启用后，管理员可以看到未经过滤的原始内容"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item
            name="treatAsWarning"
            label="仅警告而不过滤内容"
            valuePropName="checked"
            tooltip="启用后，系统只会提醒敏感内容而不会实际过滤内容"
          >
            <Switch />
          </Form.Item>
          
          <Divider orientation="left">文本过滤设置</Divider>
          
          <Form.Item
            name="filterPhoneNumbers"
            label="过滤电话号码"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item
            name="filterIdNumbers"
            label="过滤身份证号码"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item
            name="filterBankCardNumbers"
            label="过滤银行卡号"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item
            name="filterLongDigits"
            label="过滤长数字串"
            valuePropName="checked"
            tooltip="过滤长度大于8位的数字串"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item
            name="longDigitMinLength"
            label="长数字串最小长度"
            tooltip="需要过滤的连续数字最小长度"
          >
            <Slider min={6} max={16} marks={{ 6: '6', 8: '8', 12: '12', 16: '16' }} />
          </Form.Item>
          
          <Form.Item
            name="filterCustomPatterns"
            label="启用自定义过滤模式"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <Divider orientation="left">图片内容检测设置</Divider>
          
          <Form.Item
            name="enableImageContentDetection"
            label="启用图片内容检测"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item
            name="imageSensitivityLevel"
            label="图片敏感度级别"
            tooltip="敏感度越高，检测越严格，可能导致更多误判"
          >
            <Slider min={1} max={5} marks={{ 1: '低', 3: '中', 5: '高' }} />
          </Form.Item>
          
          <Form.Item
            name="detectTextInImage"
            label="检测图片中的文字"
            valuePropName="checked"
            tooltip="启用后，系统将尝试识别图片中的文字并过滤敏感内容"
          >
            <Switch />
          </Form.Item>
        </Form>
        
        <Divider orientation="left">
          自定义过滤模式
          <Button 
            type="link" 
            icon={<PlusOutlined />} 
            onClick={handleAddPattern}
            disabled={!form.getFieldValue('filterCustomPatterns')}
          >
            添加模式
          </Button>
        </Divider>
        
        <Table 
          columns={renderPatternColumns()}
          dataSource={patterns}
          rowKey="id"
          pagination={false}
          size="small"
          locale={{ emptyText: '暂无自定义过滤模式' }}
          disabled={!form.getFieldValue('filterCustomPatterns')}
        />
        
        {patterns.length > 0 && (
          <div style={{ marginTop: 16, color: '#666', fontSize: 12 }}>
            提示: 对于正则表达式模式，请使用JavaScript兼容的正则表达式语法。
          </div>
        )}
      </Card>
    </Spin>
  );
};

export default SensitiveContentSettings; 